<template>
  <div class="table-form-wrap">
    <div class="title">
      {{ formName }}
    </div>
    <div v-if="headerFormData" class="header">
      <!-- <div class="header-item"><span>工厂：</span><span>{{ headerFormData.ownedFactoryName }}</span></div> -->
      <div class="header-item">
        <span>车间：</span><span>{{ headerFormData.ownedWorkshopName }}</span>
      </div>
      <div class="header-item">
        <span>产线：</span
        ><span>{{ headerFormData.ownedProductionLineName }}</span>
      </div>
      <div class="header-item">
        <span>班组：</span>
        <span v-if="disabled">
          {{
            activeGroupitem.erpWorkGroupDesc || headerFormData.groupName || ""
          }}
        </span>
        <el-select
          v-else
          v-model="headerFormData.groupId"
          placeholder="请选择"
          size="small"
          clearable
          @change="handleGroupIdChange"
        >
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :label="item.erpWorkGroupDesc"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <!-- <div class="header-item">
        <span>班次：</span
        ><span>{{
          activeGroupitem.classesDto
            ? activeGroupitem.classesDto.classesName
            : ""
        }}</span>
      </div> -->
      <div class="header-item">
        <span>执行人：</span><span>{{ headerFormData.executorName }}</span>
      </div>
      <div class="header-item">
        <span>审核人：</span><span>{{ headerFormData.auditorName }}</span>
      </div>
      <div class="header-item">
        <span>日期：</span><span>{{ headerFormData.date }}</span>
      </div>
    </div>
    <div class="order">
      <span>工单：</span>
      <span v-if="disabled">{{
        formWorkOrder
          ? formWorkOrder.workOrderNo == ""
            ? "无"
            : formWorkOrder.workOrderName || formWorkOrder.workOrderNo
          : ""
      }}</span>
      <el-form
        v-else
        :model="orderForm"
        ref="OrderForm"
        :rules="rules"
        label-width="0"
      >
        <el-form-item label="" prop="workOrderNo">
          <el-select
            v-model="orderForm.workOrderNo"
            placeholder="请选择工单"
            size="small"
            :loading="workOrderLoading"
          >
            <el-option
              v-for="item in workOrderNoOptions"
              :key="item.id"
              :label="item.itemName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="form-template">
      <FromTemplate
        ref="FromTemplate"
        :templateConfig="templateConfig"
        :formData="templateFormData"
        :disabled="disabled"
        :isfixedRowButton="device != 'desktop'"
        @file-click="handleFileClick"
        @inited="handleFormInited"
        @add-row="handleAddRow"
      ></FromTemplate>
    </div>
  </div>
</template>
<script>
import FromTemplate from "@/views/components/formTemplate/index";
import { getIndexValue, getFile } from "@/api/taskMgmt/center";
import { orderList } from "@/api/workOrder/confirmClose";
import { listErpGroup } from "@/api/team/group";
import { isWarn } from "./warnValidate";
import { downloadFile } from "@/utils/file";
import { mapState } from "vuex";
const componentMap = {
  radio: "RADIO",
  singleSelect: "SELECT",
  text: "INPUT",
  datetime: "DATETIME",
  date: "DATE",
  multipleSelect: "CHECKBOX",
  number: "NUMBER",
  checkbox: "CHECKBOX",
  file: "UPLOAD",
  onlyread: "LABEL",
  datetimeRange: "DATETIMERANGE",
};
const defaultOrderItem = { id: "", itemName: "无" };
export default {
  components: { FromTemplate },
  props: {
    formName: {
      type: String,
      default: "",
    },
    headerForm: {
      type: Object,
      default: null,
    },
    formFieldConfig: {
      type: Object,
      default: null,
    },
    formData: {
      type: Array,
      default: null,
    },
    // 工单 {workOrderNo:"",workOrderName:""}
    formWorkOrder: {
      type: Object,
      default: null,
    },
    // 渲染模式，1-横向渲染，2-纵向渲染
    renderingMode: {
      type: String,
      default: "1",
    },
    // 表单是否可编辑
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否获取最新指标值
    isGetLastIndexValue: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      headerFormData: null,
      // 班组下拉列表
      groupList: [],
      // 工单选中值
      orderForm: {
        workOrderNo: null,
      },
      // 工单校验规则
      rules: {
        workOrderNo: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value != "") {
                callback(new Error("工单不能为空"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      // 表单配置
      templateConfig: {},
      // 表单数据
      templateFormData: null,
      // 工单下拉列表
      workOrderNoOptions: [],
      workOrderLoading: false,
    };
  },
  computed: {
    ...mapState({
      device: (state) => state.app.device,
    }),
    activeGroupitem() {
      const groupitem = this.groupList.find(
        (ele) => ele.id == this.headerFormData.groupId
      );
      return groupitem || {};
    },
  },
  methods: {
    start() {
      if (!this.templateConfig) {
        this.templateConfig = {};
        return;
      }
      if (this.renderingMode == "1") {
        this.init();
      } else {
        this.initVertical();
      }
    },
    // 获取班组列表
    getGroupList() {
      const param = {
        query: {
          searchValue: "",
          factoryDeptCode: this.headerFormData.ownedFactory,
          workshopId: this.headerFormData.ownedWorkshopId,
        },
        pageNum: 1,
        pageSize: 2000,
      };
      listErpGroup(param)
        .then((res) => {
          this.groupList = res?.rows || [];
        })
        .catch(() => {
          this.groupList = [];
        });
    },
    // 获取工单列表
    getOrderList() {
      this.workOrderLoading = true;
      const param = {
        query: {
          erpOrderNo: "",
          itemName: "",
          factoryDeptCode: this.headerFormData.ownedFactory,
          workshopId: this.headerFormData.ownedWorkshopId,
          lineId: this.headerFormData.ownedProductionLineId,
          groupId: this.headerFormData.groupId,
          orderStatus: "TO_CLOSE,CLOSED",
          taskStartTime: this.headerFormData.actualExecuteStartTime,
          taskEndTime: this.headerFormData.actualExecuteEndTime,
        },
        pageNum: 1,
        pageSize: 2000,
      };
      orderList(param)
        .then((res) => {
          if (res?.rows?.length) {
            this.workOrderNoOptions = [defaultOrderItem, ...res.rows];
          } else {
            this.workOrderNoOptions = [defaultOrderItem];
          }
        })
        .catch(() => {
          this.workOrderNoOptions = [defaultOrderItem];
        })
        .finally(() => {
          // 若某产线某班组只有一个工单，需要直接默认填充；
          // 若某产线某班组有多个工单，需要置空，用户自己选择。
          // 若某产线某班组没有工单，则默认选中“无”。
          // 若选择的工单在下拉列表中没有(工单被移除了)，或者没有选择过工单this.orderForm.workOrderNo==null，也按照上述逻辑赋予默认值
          const selectedOrder = this.workOrderNoOptions.find(
            (ele) => ele.id == this.orderForm.workOrderNo
          );
          // 除无选项外的工单
          const orderList = this.workOrderNoOptions.filter(
            (ele) => ele.id != ""
          );
          if (!selectedOrder) {
            if (orderList.length == 1) {
              this.orderForm.workOrderNo = orderList[0].id;
            } else if (orderList.length == 0) {
              this.orderForm.workOrderNo = "";
            } else {
              this.orderForm.workOrderNo = null;
            }
            if (this.$refs.OrderForm) {
              this.$refs.OrderForm.clearValidate();
            }
          }
          this.$nextTick(() => {
            this.workOrderLoading = false;
          });
        });
    },
    initVertical() {
      const headLines = this.formFieldConfig?.headLines || [];
      if (!headLines?.length) {
        return;
      }

      this.templateConfig = {
        totalCol:
          (headLines[0].headList?.length || 0) +
          (headLines[0].fieldList?.length || 0),
        title: "",
        config: [],
      };

      headLines.forEach((row, rowIndex) => {
        const standarCells = row.headList || [];
        const fieldCells = row.fieldList || [];
        const standarCellLen = standarCells.length;
        let _cells = [];
        standarCells.forEach((col, colIndex) => {
          _cells.push({
            id: `cell_${rowIndex + 1}_${colIndex + 1}`,
            content: col.label,
            controllerType: "LABEL",
            colspan: 1,
            rowspan: 1,
          });
        });
        fieldCells.forEach((col, colIndex) => {
          _cells.push({
            id: `cell_${rowIndex + 1}_${standarCellLen + colIndex + 1}`,
            attrData: col,
            content:
              col.componentType == "onlyread"
                ? col.fieldName
                : "${list[" + colIndex + "]." + col.customCode + "}",
            controllerType: componentMap[col.componentType] || "INPUT",
            options: JSON.parse(col.optionSetting || "[]").map((ele) => ({
              ...ele,
              value: ele.itemvalue,
              label: ele.itemvalue,
            })),
            required: col.isRequested == "1",
            colspan: 1,
            rowspan: 1,
            disabled: false,
            defaultValue: col.defaultValue,
            accept:
              ".jpg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpeg,.zip,.mp4,.webm,.wmv,.mpeg,.avi",
            warningVerification: {
              rule: (cell, formData) => {
                if (cell.attrData) {
                  return !isWarn(
                    cell.attrData.warnType,
                    cell.attrData.warnValue,
                    formData[cell.content]
                  );
                }
                return true;
              },
              trigger: "change",
            },
          });
        });

        this.templateConfig.config.push({
          id: `row_${rowIndex + 1}`,
          cells: _cells,
        });
      });

      // 格式化表单填写项
      const taskContentDtoList = this.formData || [];
      let _formData = [];
      taskContentDtoList.forEach((ele) => {
        if (!_formData[ele.rowNo]) {
          _formData[ele.rowNo] = {};
        }
        if (ele.attachmentId) {
          _formData[ele.rowNo][ele.fieldCode] = {
            id: ele.attachmentId,
            content: ele.attachmentContent,
            name: ele.attachmentName,
            type: "singleFile",
          };
        } else {
          _formData[ele.rowNo][ele.fieldCode] = ele.fieldValue;
        }
      });
      this.templateFormData = { list: _formData.filter((ele) => !!ele) };
    },
    init() {
      const headLines = this.formFieldConfig?.headLines || [];
      if (!headLines?.length) {
        return;
      }

      const totalCol = headLines.length;

      this.templateConfig = {
        totalCol: totalCol,
        title: "",
        config: [],
      };

      let rows = [];
      headLines.forEach((hl, hlIndex) => {
        hl.headList?.forEach((head, headIndex) => {
          if (!rows[headIndex]) {
            rows[headIndex] = {
              id: `row_${headIndex + 1}`,
              cells: [],
            };
          }
          rows[headIndex].cells[hlIndex] = {
            id: `cell_${headIndex + 1}_${hlIndex + 1}`,
            content: head.label,
            controllerType: "LABEL",
            colspan: 1,
            rowspan: 1,
          };
        });
        hl.fieldList?.forEach((field, fieldIndex) => {
          // 初始化cell
          const startIndex = (hl.headList?.length || 0) + fieldIndex;
          if (!rows[startIndex]) {
            rows[startIndex] = {
              id: `row_${startIndex + 1}`,
              cells: [],
              showDelBtn: (row, rowData) => {
                return rowData.length > 2; // 至少保留一行填写行
              },
              showAddBtn: true,
            };
          }
          rows[startIndex].cells[hlIndex] = {
            id: `cell_${startIndex + 1}_${hlIndex + 1}`,
            attrData: field,
            content:
              field.componentType == "onlyread"
                ? field.fieldName
                : "${list[" + fieldIndex + "]." + field.customCode + "}",
            controllerType: componentMap[field.componentType] || "INPUT",
            options: JSON.parse(field.optionSetting || "[]").map((ele) => ({
              ...ele,
              value: ele.itemvalue,
              label: ele.itemvalue,
            })),
            required: field.isRequested == "1",
            colspan: 1,
            rowspan: 1,
            disabled: false,
            defaultValue: field.defaultValue,
            accept:
              ".jpg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpeg,.zip,.mp4,.webm,.wmv,.mpeg,.avi",
            warningVerification: {
              rule: (cell, formData) => {
                if (cell.attrData) {
                  return !isWarn(
                    cell.attrData.warnType,
                    cell.attrData.warnValue,
                    formData[cell.content]
                  );
                }
                return true;
              },
              trigger: "change",
            },
          };
        });
      });

      // 格式化表单填写项
      const taskContentDtoList = this.formData || [];
      let _formData = [];
      taskContentDtoList.forEach((ele) => {
        if (!_formData[ele.rowNo]) {
          _formData[ele.rowNo] = {};
        }
        if (ele.attachmentId) {
          _formData[ele.rowNo][ele.fieldCode] = {
            id: ele.attachmentId,
            content: ele.attachmentContent,
            name: ele.attachmentName,
            type: "singleFile",
          };
        } else {
          _formData[ele.rowNo][ele.fieldCode] = ele.fieldValue;
        }
      });
      this.templateFormData = { list: _formData.filter((ele) => !!ele) };

      // 最后一行允许添加行
      // rows[rows.length - 1].listSizeMode = "available";
      // 多行
      if (this.templateFormData?.list?.length > 1) {
        rows[rows.length - 1].copyValuesRows = 1;
      }

      this.templateConfig.config = rows;
    },
    // 切换班组
    handleGroupIdChange() {
      // 清空工单
      this.orderForm.workOrderNo = null;
      // 更新工单
      this.getOrderList();
    },
    // 获取内容数据时，是否先校验，校验失败不会返回数据
    getSubmitData(isValidate = true) {
      if (isValidate) {
        // 校验工单，必填
        let orderFlag = true;
        this.$refs.OrderForm.validate((flag) => {
          orderFlag = flag;
        });
        if (!orderFlag) {
          return;
        }
        // 校验填写的表单
        const validCell = this.$refs.FromTemplate.validate();
        if (!validCell.flag) {
          return null;
        }
      }
      const data = this.$refs.FromTemplate.getSubmitFormData();

      let attachmentSize = 0; // 附件大小
      let taskContentDtoList = [];
      if (data.list?.length) {
        for (let i = 0; i < data.list.length; i++) {
          const row = data.list[i];
          for (const key in row) {
            if (Object.hasOwnProperty.call(row, key)) {
              const value = row[key];
              let rowparam = {};
              if (
                Object.prototype.toString.call(value) == "[object Object]" &&
                value.type == "singleFile"
              ) {
                // 文件类型
                rowparam = {
                  rowNo: i + 1,
                  fieldCode: key,
                  attachmentId: value.id,
                  attachmentName: value.name,
                  attachmentContent: value.content,
                };
                attachmentSize += (value.content.length || 0) * 0.75; //累计附件大小
              } else {
                rowparam = {
                  rowNo: i + 1,
                  fieldCode: key,
                  fieldValue: value,
                };
              }
              taskContentDtoList.push(rowparam);
            }
          }
        }
      }

      // 校验附件大小
      console.log(attachmentSize);
      if (attachmentSize / 1024 / 1024 > 8) {
        this.msgWarning("上传的附件大小超过限制！");
        return null;
      }

      return {
        taskContentDtoList,
        workOrderNo: this.orderForm.workOrderNo,
        groupId: this.headerFormData.groupId,
        groupName: this.activeGroupitem.erpWorkGroupDesc,
        className: this.activeGroupitem.classesDto?.classesName,
        classId: this.activeGroupitem.classesId,
      };
    },
    handleFileClick(file, cell) {
      if (!file?.id) {
        return;
      }
      getFile(file.id).then((res) => {
        downloadFile(res.file, file.name);
      });
    },
    // 初始化后，获取指标值
    handleFormInited(rowData, oldForm) {
      // 只有执行的时候才获取指标
      if (!this.isGetLastIndexValue) {
        return;
      }
      if (!rowData?.length) {
        return;
      }
      rowData.forEach((row) => {
        this.getCellIndexValue(row.cells, oldForm);
      });
    },
    // 添加行回调，更新指标
    handleAddRow(newOld) {
      // 只有执行的时候才获取指标
      if (!this.isGetLastIndexValue) {
        return;
      }
      this.getCellIndexValue(newOld?.cells);
    },
    // 遍历单元格获取指标
    getCellIndexValue(cells, oldForm) {
      // 只有执行的时候才获取指标
      if (!this.isGetLastIndexValue) {
        return;
      }
      if (!cells?.length) {
        return;
      }
      cells.forEach((cell) => {
        if (!cell.attrData?.associativePointer) {
          return;
        }
        // 保存的表单值
        const keys = cell.content.match(/(?<=\$\{)[a-zA-Z0-9_\.\[\]]+(?=\})/);
        if (!keys?.length) {
          return;
        }
        let key = keys[0];
        let formValue = "";
        try {
          formValue = eval(`oldForm.${key}`);
        } catch (error) {
          formValue = "";
        }

        // 有关联指标，且没有修改保存过值，则获取最近一次指标值
        if (!formValue) {
          const param = {
            indexConfigId: cell.attrData.associativePointer,
            datetime: this.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
          };
          getIndexValue(param).then((res) => {
            if (
              res?.code == 200 &&
              res?.data != null &&
              res?.data != undefined
            ) {
              if (this.$refs.FromTemplate) {
                // 刷新数据
                this.$refs.FromTemplate.updateFormObj(
                  cell.content,
                  res.data.toString()
                );
              }
            }
          });
        }
      });
    },
  },
  watch: {
    formFieldConfig: {
      handler() {
        this.start();
      },
      immediate: true,
    },
    headerForm: {
      handler(newVal) {
        if (!newVal?.ownedProductionLineId) {
          return;
        }
        this.headerFormData = { ...newVal };
        // 获取班组列表
        this.getGroupList();
        // 获取工单列表
        this.getOrderList();
      },
      immediate: true,
    },
    formWorkOrder: {
      handler(newVal) {
        if (newVal) {
          this.orderForm.workOrderNo = newVal.workOrderNo;
        } else {
          this.orderForm.workOrderNo = null;
        }
      },
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.table-form-wrap {
  .title {
    text-align: center;
    margin-bottom: 20px;
    font-size: 16px;
    color: #303133;
  }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
    gap: 16px;
    // flex-wrap: wrap;
    &-item {
      white-space: nowrap;
    }
  }
  .order {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 12px;
    ::v-deep .el-form-item {
      margin: 0;
    }
  }
}
</style>
